<?php

namespace RjYst\Category\Services;

use Illuminate\Support\Facades\File;

class DatabaseConfigUpdater
{
    /**
     * 更新数据库配置文件
     */
    public static function updateDatabaseConfig()
    {
        $configPath = config_path('database.php');

        if (!File::exists($configPath)) {
            throw new \Exception('数据库配置文件不存在: ' . $configPath);
        }

        $content = File::get($configPath);

        // 检查是否已经存在 rjmysql 配置
        if (self::hasRjmysqlConfig()) {
            return false; // 已存在，不需要更新
        }

        // 修复可能存在的格式问题
        $content = self::fixDatabaseConfig($content);

        // 使用改进的插入方法
        return self::insertRjmysqlConfig($content, $configPath);
    }

    /**
     * 修复数据库配置格式问题
     */
    private static function fixDatabaseConfig($content)
    {
        // 检查并修复可能的格式问题

        // 1. 修复 mysql 配置中可能缺少的结束括号
        $pattern = '/(\s*\'mysql\'\s*=>\s*\[[\s\S]*?\'options\'\s*=>\s*[^\]]*\],)(\s*\'rjmysql\'\s*=>\s*\[[\s\S]*?\],\s*\],)/';

        if (preg_match($pattern, $content, $matches)) {
            // 发现格式错误，修复它
            $mysqlConfig = $matches[1];
            $rjmysqlConfig = $matches[2];

            // 确保 mysql 配置正确结束
            $fixedMysqlConfig = $mysqlConfig . "\n        ],";

            // 提取并格式化 rjmysql 配置
            $fixedRjmysqlConfig = self::extractAndFormatRjmysqlConfig($rjmysqlConfig);

            // 替换原配置
            $content = str_replace($matches[0], $fixedMysqlConfig . "\n" . $fixedRjmysqlConfig, $content);
        }

        return $content;
    }

    /**
     * 提取并格式化 rjmysql 配置
     */
    private static function extractAndFormatRjmysqlConfig($rjmysqlConfig)
    {
        // 从错误的嵌套中提取配置内容
        $pattern = '/\'rjmysql\'\s*=>\s*\[([\s\S]*?)\],\s*\],/';

        if (preg_match($pattern, $rjmysqlConfig, $matches)) {
            $configContent = $matches[1];

            return "        'rjmysql' => [\n" . $configContent . "        ],";
        }

        return '';
    }

    /**
     * 插入 rjmysql 配置
     */
    private static function insertRjmysqlConfig($content, $configPath)
    {
        // 定义正确格式的 rjmysql 配置
        $rjmysqlConfig = "        'rjmysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_RJ', 'forge'),
            'username' => env('DB_USERNAME_RJ', 'forge'),
            'password' => env('DB_PASSWORD_RJ', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],";

        // 策略1: 在 mysql 配置后插入（最精确的匹配）
        $mysqlPattern = '/(\s*\'mysql\'\s*=>\s*\[[\s\S]*?\'options\'\s*=>\s*extension_loaded\(\'pdo_mysql\'\)\s*\?\s*array_filter\(\[[\s\S]*?\]\)\s*:\s*\[\],\s*\],)/';

        if (preg_match($mysqlPattern, $content, $matches)) {
            $replacement = $matches[1] . "\n" . $rjmysqlConfig;
            $content = str_replace($matches[1], $replacement, $content);
            File::put($configPath, $content);
            return true;
        }

        // 策略2: 更通用的 mysql 配置匹配
        $generalMysqlPattern = '/(\s*\'mysql\'\s*=>\s*\[[\s\S]*?\],)/';

        if (preg_match($generalMysqlPattern, $content, $matches)) {
            $replacement = $matches[1] . "\n" . $rjmysqlConfig;
            $content = str_replace($matches[1], $replacement, $content);
            File::put($configPath, $content);
            return true;
        }

        // 策略3: 在 pgsql 前插入
        if (self::insertBeforePgsql($content, $rjmysqlConfig)) {
            File::put($configPath, $content);
            return true;
        }

        return false;
    }

    /**
     * 在 pgsql 配置前插入
     */
    private static function insertBeforePgsql(&$content, $rjmysqlConfig)
    {
        $pattern = '/(\s+)(\'pgsql\'\s*=>\s*\[)/';

        if (preg_match($pattern, $content)) {
            $content = preg_replace($pattern, "\n" . trim($rjmysqlConfig) . "\n$1$2", $content);
            return true;
        }

        return false;
    }

    /**
     * 重构整个数据库配置（最可靠的方法）
     */
    public static function updateDatabaseConfigReliable()
    {
        $configPath = config_path('database.php');

        if (!File::exists($configPath)) {
            throw new \Exception('数据库配置文件不存在: ' . $configPath);
        }

        // 检查是否已经存在 rjmysql 配置
        if (self::hasRjmysqlConfig()) {
            return false;
        }

        // 读取当前配置
        $content = File::get($configPath);

        // 使用字符串替换的方式，确保正确的格式
        $searchPattern = "        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],";

        $replacement = "        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],
        'rjmysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_RJ', 'forge'),
            'username' => env('DB_USERNAME_RJ', 'forge'),
            'password' => env('DB_PASSWORD_RJ', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],";

        // 执行替换
        $newContent = str_replace($searchPattern, $replacement, $content);

        if ($newContent !== $content) {
            File::put($configPath, $newContent);
            return true;
        }

        // 如果精确匹配失败，使用正则表达式方法
        return self::insertRjmysqlConfig($content, $configPath);
    }

    /**
     * 检查 rjmysql 配置是否已存在（更精确）
     */
    public static function hasRjmysqlConfig()
    {
        $configPath = config_path('database.php');

        if (!File::exists($configPath)) {
            return false;
        }

        $content = File::get($configPath);

        // 检查是否存在正确格式的 rjmysql 配置
        return preg_match('/\s*\'rjmysql\'\s*=>\s*\[[\s\S]*?\],/', $content);
    }

    /**
     * 移除 rjmysql 配置
     */
    public static function removeRjmysqlConfig()
    {
        $configPath = config_path('database.php');

        if (!File::exists($configPath)) {
            return false;
        }

        $content = File::get($configPath);

        // 删除 rjmysql 配置块（包括可能的错误格式）
        $patterns = [
            // 正确格式
            '/\s*\'rjmysql\'\s*=>\s*\[[\s\S]*?\],\s*/',
            // 错误嵌套格式
            '/\'rjmysql\'\s*=>\s*\[[\s\S]*?\],\s*\],/',
        ];

        foreach ($patterns as $pattern) {
            $content = preg_replace($pattern, '', $content);
        }

        // 修复可能的格式问题
        $content = self::fixBracketsAndFormatting($content);

        File::put($configPath, $content);
        return true;
    }

    /**
     * 修复括号和格式问题
     */
    private static function fixBracketsAndFormatting($content)
    {
        // 确保 mysql 配置正确结束
        $content = preg_replace('/(\s*\'options\'\s*=>\s*extension_loaded\(\'pdo_mysql\'\)\s*\?\s*array_filter\(\[[\s\S]*?\]\)\s*:\s*\[\],)\s*\],\s*\],/', '$1' . "\n        ],", $content);

        return $content;
    }
}
